import React, { useEffect, useState } from "react";
import { ChatMessageType, RenderItem } from "../../../../serve/interfaces";
import { get as _get } from 'lodash'
import { Fetch } from "@/apis/Fetch";
import Link from "./Link";
import { __ON_LINK__ } from "@/common";
import { Toast } from "antd-mobile";
import { ExclamationTriangleOutline } from "antd-mobile-icons";

export default (props: RenderItem<ChatMessageType.LINK_WITH_TITLE>) => {
  const { body, render } = props
  const [title, setTitle] = useState('')

  useEffect(function () {
    const { url, template } = render
    Fetch<any>(url).then(res => {
      setTitle(template.replace(/\$\{([\w\.]+)\}/g, (_, k) => _get(res, k) || ''))
    })
  }, [])
  return title ? <div style={{ background: '#FACD91', padding: 6, borderRadius: 6 }}>
    {title}
    <br />
    <a href={body} target="_blank" onClick={e => {
    __ON_LINK__?.(body, true, (content) => Toast.show({
      icon: <ExclamationTriangleOutline />,
      content,
    }))(e.nativeEvent)
  }}>点击查看</a>
  </div> : <Link body={body} type={ChatMessageType.LINK}/>
}
